package com.tyk.bookstore.front.auth.strategy.impl;


import com.tyk.bookstore.front.auth.manager.AuthRedisManager;
import com.tyk.bookstore.front.auth.model.entity.MemberDo;
import com.tyk.bookstore.front.auth.model.query.LoginCodeQuery;
import com.tyk.bookstore.front.auth.repository.MemberAuthRepository;
import com.tyk.bookstore.front.auth.strategy.LoginAction;
import com.tyk.bookstore.front.auth.util.ParamUtil;
import com.tyk.bookstore.front.common.core.model.result.CommonResultEnum;
import com.tyk.bookstore.front.common.core.util.AssertUtil;
import com.tyk.bookstore.front.common.core.util.ObjUtil;
import com.tyk.bookstore.front.common.dal.mapper.dto.SinDto;
import com.tyk.bookstore.front.common.other.code.msg.model.enume.MsgCodeType;
import com.tyk.bookstore.front.member.model.result.MemberResultEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.math.BigInteger;

@Component
@RequiredArgsConstructor
public class EmailCodeLoginAction implements LoginAction<LoginCodeQuery> {

    private final MemberAuthRepository memberAuthRepository;
    private final AuthRedisManager authRedisManager;


    @Override
    public boolean check(LoginCodeQuery query) {
        return ParamUtil.checkEmail(query.getPrincipal()) && ParamUtil.checkCode(query.getCertificate());
    }

    @Override
    public Long getMemberId(LoginCodeQuery query) {

        // 校验短信验证码
        String code = authRedisManager.getLoginMsgCode(MsgCodeType.EMAIL_QQ, query.getVerifyCode(), query.getPrincipal());
        boolean f1 = ObjUtil.equal(code, query.getCertificate());
        AssertUtil.isTrue(f1, CommonResultEnum.CODE_MSG_EMAIL_ERROR_OR_EXPIRED);

        // 校验邮箱
        SinDto<BigInteger> dto = memberAuthRepository.selectSin1Eq(
                MemberDo::getId, MemberDo::getEmail, query.getPrincipal(), MemberDo.class
        );
        AssertUtil.notNull(dto, MemberResultEnum.EMAIL_NOT_BOUND);

        // 返回会员ID
        return dto.getV1().longValue();
    }
}
